package com.shaoshaohuo.app.ui.shipper;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.adapter.AddedServiceSelectListAdapter;
import com.shaoshaohuo.app.constant.CarOption;
import com.shaoshaohuo.app.constant.ExtraName;
import com.shaoshaohuo.app.entity.AddedService;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.Coupon;
import com.shaoshaohuo.app.entity.Order.CarUserInfo;
import com.shaoshaohuo.app.entity.OrderDetail;
import com.shaoshaohuo.app.entity.OrderDetailEntity;
import com.shaoshaohuo.app.framework.AccountManager;
import com.shaoshaohuo.app.net.HttpRequest.RequestListener;
import com.shaoshaohuo.app.net.RequestService;
import com.shaoshaohuo.app.ui.BaseActivity;
import com.shaoshaohuo.app.ui.PhotoBrowseActivity;
import com.shaoshaohuo.app.ui.ec.SupplyDetailActivity;
import com.shaoshaohuo.app.utils.AreaUtil;
import com.shaoshaohuo.app.utils.ArithUtil;
import com.shaoshaohuo.app.utils.AudioPlayManager;
import com.shaoshaohuo.app.utils.ImageLoadUtil;
import com.shaoshaohuo.app.utils.StringHelper;
import com.shaoshaohuo.app.utils.im.IMFactory;
import com.shaoshaohuo.app.view.MeasureGridView;
import com.shaoshaohuo.app.view.TopbarView;
import com.shaoshaohuo.app.wxapi.PayActivity;

/**
 * @ClassName PayOrderActivity
 * @Decription 支付订单
 * @2015-8-5 上午12:54:33
 */
public class PayOrderActivity extends BaseActivity implements OnClickListener {

	private TopbarView mTopbarView;

	private ImageView mCarUserHeadImage;
	private TextView mCarUserNameText;
	private TextView mCarUserPhoneText;
	private ImageView mCallPhoneImage;
	
	private TextView mYunfeiText;
	
	private TextView mStartAddrssText;
	private TextView mEndAddressText;
	private TextView mSendTimeText;
	private TextView mReceiveTimeText;
	
	private TextView mCargoTypeText;
	private View mOrderImageLayout;
	private ImageView mPhoto1Image;
	private ImageView mPhoto2Image;
	private ImageView mPhoto3Image;
	
	private EditText mContactPhoneEdit;
	
	private TextView mBxDeleteButton;
	private TextView mBxAddButton;
	private TextView mBxCountText;
	private TextView mBxCostText;
	private View mCouponLayout;
	private TextView mCouponText;
	private TextView mCostDetailText;
	private TextView mCostTotalText;
	
	private MeasureGridView mAddedServiceGv;
	
	private Button mPayButton;

	private String orderid;

	private OrderDetail data;
	
	private AudioPlayManager audioPlayManager;
	
	private int bxnum = 0;
	private double bxPrice = 0;
	private double bxTotal = 0;
	private double beTotal = 0;
	private double beMoney = 0;
	private double orderTotal = 0;
	private double couponTotal = 0;

	private Coupon coupon;
	private ImageView mCallChatImage;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_pay_order);
		
		initData();
		initView();
		setUpView();
		requestData();
	}

	private void initData() {
		orderid = getIntent().getStringExtra(ExtraName.orderid);
		audioPlayManager = new AudioPlayManager(this);
		beMoney = Double.parseDouble(AccountManager.getBaoxian().getBxmoney());
	}
	
	private void initView() {
		mTopbarView = (TopbarView) this.findViewById(R.id.topbar);
		mAddedServiceGv = (MeasureGridView) this.findViewById(R.id.gv_service_list);
		mPayButton = (Button) this.findViewById(R.id.button_next);
		
		mYunfeiText = (TextView) this.findViewById(R.id.textview_yunfei);

		mStartAddrssText = (TextView) this.findViewById(R.id.textview_start_address);
		mEndAddressText = (TextView) this.findViewById(R.id.textview_end_address);
		mSendTimeText = (TextView) this.findViewById(R.id.textview_send_time);
		mReceiveTimeText = (TextView) this.findViewById(R.id.textview_receive_time);

		mOrderImageLayout = this.findViewById(R.id.layout_order_image);

		mCarUserHeadImage = (ImageView) this.findViewById(R.id.imageview_car_user_headview);
		mCarUserNameText = (TextView) this.findViewById(R.id.textview_car_username);
		mCarUserPhoneText = (TextView) this.findViewById(R.id.textview_car_phone);
		mCallPhoneImage = (ImageView) this.findViewById(R.id.imageview_call_phone);

		mCargoTypeText = (TextView) this.findViewById(R.id.textview_cargo_type);
		mPhoto1Image = (ImageView) this.findViewById(R.id.imageview_photo1);
		mPhoto2Image = (ImageView) this.findViewById(R.id.imageview_photo2);
		mPhoto3Image = (ImageView) this.findViewById(R.id.imageview_photo3);

		mContactPhoneEdit = (EditText) this.findViewById(R.id.edittext_contact_phone);
		mBxCostText = (TextView) this.findViewById(R.id.textview_baoxian_money);
		
		mCouponLayout = this.findViewById(R.id.layout_coupon);
		mCouponText = (TextView) this.findViewById(R.id.textview_coupon);
		mCostDetailText = (TextView) this.findViewById(R.id.textview_cost);
		mCostTotalText = (TextView) this.findViewById(R.id.textview_cost_total);
		
		mBxDeleteButton = (TextView) this.findViewById(R.id.button_jian);
		mBxAddButton = (TextView) this.findViewById(R.id.button_jia);
		mBxCountText = (TextView) this.findViewById(R.id.textview_baoxian_count);
		
		mAddedServiceGv = (MeasureGridView) this.findViewById(R.id.gv_service_list);

		mCallChatImage = (ImageView) this.findViewById(R.id.imageview_call_chat);
	}

	private void setUpView() {
		mTopbarView.setCenterText("订单确认");
		mTopbarView.setLeftView(true, true);

//		List<AddedService> list = DaoUtils.findAllAddedService();
//		AddedServiceListAdapter serviceAdapter = new AddedServiceListAdapter<>(this, list, false);
//		mAddedServiceGv.setAdapter(serviceAdapter);
		
		mPayButton.setOnClickListener(this);
		mCallPhoneImage.setOnClickListener(this);
		mBxDeleteButton.setOnClickListener(this);
		mBxAddButton.setOnClickListener(this);
		mCouponLayout.setOnClickListener(this);
		
		mPhoto1Image.setOnClickListener(this);
        mPhoto2Image.setOnClickListener(this);
        mPhoto3Image.setOnClickListener(this);

		mCallChatImage.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				IMFactory.openChat(PayOrderActivity.this, data.getCaruserid());
			}
		});
	}
	
	private void requestData() {
		startLoadingDialog();
		RequestService.getInstance().getOrderDetail(this, orderid, OrderDetailEntity.class, new RequestListener() {
			
			@Override
			public void onSuccess(int requestCode, BaseEntity resultData) {
				dismissLoadingDialog();
				if(resultData.isOk()){
					OrderDetailEntity entity = (OrderDetailEntity) resultData;
					updateUi(entity);
				}else{
					showToast(resultData.getMsg());
				}
			}
			
			@Override
			public void onFailed(int requestCode, Exception error, String msg) {
				dismissLoadingDialog();
				showToast(msg);
			}
		});
	}

	protected void updateUi(OrderDetailEntity entity) {
		data = entity.getData();
		if (data == null) {
			showToast("无此订单!");
			finish();
			return;
		}

		mYunfeiText.setText("运费:" + data.getOrdertotal());

		CarUserInfo caruserinfo = data.getCaruserinfo();
		if (caruserinfo != null) {
//			LoadUtils.getInstance().loadImage(mCarUserHeadImage, caruserinfo.getAvatar(), 0, 100);
			ImageLoader.getInstance().displayImage(caruserinfo.getAvatar(), mCarUserHeadImage,ImageLoadUtil.getDisplayImageOptions(R.drawable.icon_default_headimage, 180));
			mCarUserNameText.setText(caruserinfo.getRealname());
			mCarUserPhoneText.setText(caruserinfo.getPhone());
			mCarUserPhoneText.setVisibility(View.GONE);
		}

		mStartAddrssText.setText(AreaUtil.getAreaFullname(data.getOrigincityid()) + data.getOriginaddress());
		mEndAddressText.setText(AreaUtil.getAreaFullname(data.getReceivecityid()) + data.getReceiveaddress());

		mSendTimeText.setText( data.getOrigintime());
		mReceiveTimeText.setText(data.getReceivetime());


		if ("1".equals(data.getShipptype())) {
            mCargoTypeText.setText(CarOption.cargoItems[0]);
        } else if ("2".equals(data.getShipptype())) {
        	StringBuilder sb = new StringBuilder();
        	sb.append(CarOption.cargoItems[1] + "/" + data.getShippweight() + "kg");
        	if(Double.parseDouble(data.getShipparea())>0){
        		sb.append("/" + data.getShipparea() + "m³");
        	}
        	if(Double.parseDouble(data.getShipplength())>0){
        		sb.append("/" + data.getShipplength() + "m");
        	}
            mCargoTypeText.setText(sb.toString());
        } else if ("3".equals(data.getShipptype())) {
        	StringBuilder sb = new StringBuilder();
        	sb.append(CarOption.cargoItems[2] + "/" + data.getShipparea() + "m³");
        	if(Double.parseDouble(data.getShippweight())>0){
        		sb.append("/" + data.getShippweight() + "kg");
        	}
        	if(Double.parseDouble(data.getShipplength())>0){
        		sb.append("/" + data.getShipplength() + "m");
        	}
            mCargoTypeText.setText(sb.toString());
        	
//            mCargoTypeText.setText(CarOption.cargoItems[2] + "/" + Data.getShipparea() + "m³");
        }
		String[] shippimg = data.getShippimg();
		if (shippimg.length > 0) {
			mOrderImageLayout.setVisibility(View.VISIBLE);
			ImageLoader.getInstance().displayImage(shippimg[0], mPhoto1Image,ImageLoadUtil.build);
            if (shippimg.length > 1) {
//              LoadUtils.getInstance().loadImage(mPhoto2Image, shippimg[1]);
                ImageLoader.getInstance().displayImage(shippimg[1], mPhoto2Image,ImageLoadUtil.build);
                if (shippimg.length > 2) {
//                  LoadUtils.getInstance().loadImage(mPhoto3Image, shippimg[2]);
                    ImageLoader.getInstance().displayImage(shippimg[2], mPhoto3Image,ImageLoadUtil.build);
                }
            }
		} else {
			mOrderImageLayout.setVisibility(View.GONE);
		}

		mContactPhoneEdit.setText(data.getOriginphone());
		
		bxnum = Integer.parseInt(data.getBxnum());
		bxPrice = Double.parseDouble(data.getBxprice());
		bxTotal = Double.parseDouble(data.getBxtotal());
		beTotal = Double.parseDouble(data.getBetotal());
		orderTotal = Double.parseDouble(data.getTotal());
		
		mBxCountText.setText(bxnum+"");
		mBxCostText.setText("￥"+bxTotal+"元,保金"+(beTotal/10000)+"万元");
		mCostDetailText.setText("运费￥"+data.getOrdertotal()+"+保险费￥"+bxTotal+"-代金券￥0");
		mCostTotalText.setText("合计:￥"+orderTotal);
		
		if ("-1".equals(data.getCaruserstatus())) {
			mCallPhoneImage.setVisibility(View.GONE);
		} else {
			mCallPhoneImage.setVisibility(View.VISIBLE);
		}
		
		AddedServiceSelectListAdapter<AddedService> serviceAdapter = new AddedServiceSelectListAdapter<>(this, data.getAttach(),
				false);
		mAddedServiceGv.setAdapter(serviceAdapter);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.button_next:
			if(data == null){
				showToast(R.string.please_check_network);
				return;
			}
			
			String contactPhone = mContactPhoneEdit.getText().toString().trim();
			if (TextUtils.isEmpty(contactPhone)) {
				showToast("请输入联系人电话");
				return;
			}
			if (!StringHelper.isPhoneNumber(contactPhone)) {
				showToast("请输入合格的联系人电话");
				return;
			}
			
			Intent intent = new Intent(this,PayActivity.class);
			intent.putExtra(ExtraName.orderid, orderid+"");
			intent.putExtra(ExtraName.totalPrice, orderTotal+"");
			if(coupon!=null){
				intent.putExtra(ExtraName.couponid, coupon.getCouponid());
			}else{
				intent.putExtra(ExtraName.couponid, "");
			}
			intent.putExtra(ExtraName.origincontact, data.getOrigincontact());
			intent.putExtra(ExtraName.originphone, contactPhone);
			intent.putExtra(ExtraName.bxprice, bxPrice+"");
			intent.putExtra(ExtraName.bxnum, bxnum+"");
			startActivity(intent);
			break;
		case R.id.imageview_call_phone:
			callCarUser();
			break;
		case R.id.button_jian:
			if (bxnum <= 0) {
				return;
			}
			bxnum -= 1;
			mBxCountText.setText(bxnum + "");
			
			bxTotal = ArithUtil.mul(bxnum, bxPrice);
			orderTotal = ArithUtil.sub(orderTotal, bxPrice);
			beTotal = ArithUtil.sub(beTotal, beMoney);
			
			mBxCostText.setText("￥"+bxTotal+"元,保金"+(beTotal/10000)+"万元");
			mCostDetailText.setText("运费￥"+data.getOrdertotal()+"+保险费￥"+bxTotal+"-代金券￥"+couponTotal);
			mCostTotalText.setText("合计:￥"+orderTotal);
			break;
		case R.id.button_jia:
			bxnum += 1;
			mBxCountText.setText(bxnum + "");
			
			bxTotal = ArithUtil.mul(bxnum, bxPrice);
            orderTotal = ArithUtil.add(orderTotal, bxPrice);
            beTotal = ArithUtil.add(beTotal, beMoney);
			
			mBxCostText.setText("￥"+bxTotal+"元,保金"+(beTotal/10000)+"万元");
			mCostDetailText.setText("运费￥"+data.getOrdertotal()+"+保险费￥"+bxTotal+"-代金券￥"+couponTotal);
			mCostTotalText.setText("合计:￥"+orderTotal);
			break;
		case R.id.layout_coupon:
			selectCoupon();
			break;
		case R.id.imageview_photo1:
            if(data!=null && data.getShippimg().length >0){
                Intent intent1 = new Intent(this,PhotoBrowseActivity.class);
                intent1.putExtra(ExtraName.photoArray, data.getShippimg());
                intent1.putExtra(ExtraName.photoIndex, 0);
                startActivity(intent1);
            }
            break;
        case R.id.imageview_photo2:
            if(data!=null && data.getShippimg().length >1){
                Intent intent1 = new Intent(this,PhotoBrowseActivity.class);
                intent1.putExtra(ExtraName.photoArray, data.getShippimg());
                intent1.putExtra(ExtraName.photoIndex, 1);
                startActivity(intent1);
            }
            break;
        case R.id.imageview_photo3:
            if(data!=null && data.getShippimg().length >2){
                Intent intent1 = new Intent(this,PhotoBrowseActivity.class);
                intent1.putExtra(ExtraName.photoArray, data.getShippimg());
                intent1.putExtra(ExtraName.photoIndex, 2);
                startActivity(intent1);
            }
            break;
		}
	}
	
	private void selectCoupon() {
//		showToast("选择优惠券");
		Intent intent = new Intent(this,SelectCouponActivity.class);
		startActivityForResult(intent, 0);
	}
	
	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		// TODO Auto-generated method stub
		super.onActivityResult(arg0, arg1, arg2);
		if(arg1 == RESULT_OK){
		    if(arg2.getSerializableExtra(ExtraName.coupon) == null){
	            couponTotal = 0;
	            orderTotal = ArithUtil.add(Double.parseDouble(data.getTotal()), bxTotal);
	            mCouponText.setText("");
	            mCostDetailText.setText("运费￥"+data.getOrdertotal()+"+保险费￥"+bxTotal);
	            mCostTotalText.setText("合计:￥"+orderTotal);
	            return;
		    }
		    
		    Coupon c = (Coupon) arg2.getSerializableExtra(ExtraName.coupon);
		    
		    if(coupon == null || !coupon.getId().equals(c.getId())){
		        
		        if(coupon != null){
		            orderTotal = ArithUtil.add(orderTotal, couponTotal);
		            coupon = c;
                    couponTotal = Double.parseDouble(coupon.getTotal());
                    orderTotal = ArithUtil.sub(orderTotal, couponTotal);
                    
                    mCouponText.setText(coupon.getContent()+"￥"+couponTotal);
                    mCostDetailText.setText("运费￥"+data.getOrdertotal()+"+保险费￥"+bxTotal+"-代金券￥"+couponTotal);
                    mCostTotalText.setText("合计:￥"+orderTotal);
		        }else{
		            coupon = c;
		            couponTotal = Double.parseDouble(coupon.getTotal());
		            orderTotal = ArithUtil.sub(orderTotal, couponTotal);
		            
		            mCouponText.setText(coupon.getContent()+"￥"+couponTotal);
		            mCostDetailText.setText("运费￥"+data.getOrdertotal()+"+保险费￥"+bxTotal+"-代金券￥"+couponTotal);
		            mCostTotalText.setText("合计:￥"+orderTotal);
		        }
		    }
		    
//			showToast(coupon.getContent());
			
		}
	}

	private void callCarUser() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("确定呼叫车主 " + data.getCaruserinfo().getRealname() + "?");
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + data.getCaruserinfo().getPhone()));
				startActivity(intent);
			}
		});
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {

			}
		});
		builder.create().show();
	}
	
	@Override
	protected void onDestroy() {
	    if(audioPlayManager.isPlaying()){
            audioPlayManager.stopPlaying();
        }
	    super.onDestroy();
	}
	
}
